package com.woniuxy.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.entity.Yi;
import com.woniuxy.entity.dto.WaybillDTO;
import com.woniuxy.entity.dto.YiByWaybillDTO;
import com.woniuxy.entity.dto.YiDTO;
import com.woniuxy.entity.dto.YiData;
import com.woniuxy.mapper.YiMapper;
import com.woniuxy.service.YiService;
import com.woniuxy.util.*;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

/**
 * @program: tsm
 * @description:
 * @create: 2024-10-18 14:49
 **/
@Service
public class YiServiceImpl implements YiService {
    @Resource
    private YiMapper yiMapper;
    @Resource
    private ExportService exportService;

    /**
     * 分页连表查询所有需要内容
     *
     * @param pageData
     * @return
     */
    @Override
    public ResponseData<?> queryException(PageData<YiDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<YiDTO> yiDTOS = yiMapper.queryException(pageData.getParam());

        PageInfo pageInfo = new PageInfo(yiDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    /**
     * ???
     *
     */
    @Override
    public ResponseData<?> queryException2() {
        List<YiDTO> yiDTOS = yiMapper.queryException(null);
        int totalSize = yiMapper.queryAll();

        // 创建并设置 YiDTO 对象
        YiDTO yiDTO = new YiDTO();
        yiDTO.setSize1(String.valueOf(yiDTOS.size()));
        yiDTO.setSize2(String.valueOf(totalSize));

        // 计算异常率，避免除以 0
        if (totalSize > 0) {
            double yichanglv = ((double) yiDTOS.size() / totalSize) * 100; // 计算百分比
            yiDTO.setYichanglv(String.format("%.2f%%", yichanglv));  // 格式化为百分数（保留 2 位小数）
        } else {
            yiDTO.setYichanglv("0.00%"); // 若总记录数为 0，异常率设为 0%
        }

        String yichanglv = yiDTO.getYichanglv();

        // 插入记录
        yiMapper.addByYiT(yiDTO);

        PageInfo pageInfo = new PageInfo(yiDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    /**
     * 统计表
     *
     * @param pageData
     * @return
     */
    @Override
    public ResponseData<?> queryET(PageData<YiDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<YiDTO> yiDTOS = yiMapper.queryExceptionT(pageData.getParam());
        PageInfo pageInfo = new PageInfo(yiDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    /**
     * 上报异常（新增）
     *
     * @param yiDTO
     * @return
     */
    @Override
    public ResponseData<?> add(YiDTO yiDTO) {
        Yi yi = new Yi(yiDTO);

        //雪花id
//        SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
//        String s = "YC";
//        String xueHuaId = s + sg.nextId();
//        yi.setId(xueHuaId);

        //上报人id
        Long userId = UserContext.getUserId();
        yi.setProcessorId(String.valueOf(userId));

        return new ResponseData<>().ok(yiMapper.add(yi));
    }

    /**
     * 上报功能点击新增id
     *
     * @param yiDTO
     * @return
     */
    @Override
    public ResponseData<?> addIdByImg(YiDTO yiDTO) {
        Yi yi = new Yi(yiDTO);

        //雪花id
        SnowflakeIdGenerator sg = new SnowflakeIdGenerator();
        String s = "YC";
        String xueHuaId = s + sg.nextId();
        yi.setId(xueHuaId);
        yiMapper.addIdByImg(yi);

        return new ResponseData<>().ok(yi.getId());
    }

    /**
     * 按id查询
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData<?> queryById(String id) {
        return new ResponseData<>().ok(yiMapper.queryById(id));
    }

    /**
     * 修改finish（异常状态）
     *
     * @param yiDTO
     * @return
     */
    @Override
    public ResponseData<?> updateByFinish(YiDTO yiDTO) {
        //处理人id
        Long userId = UserContext.getUserId();
        yiDTO.setPoweruserId(String.valueOf(userId));

        String processingStatus = yiDTO.getProcessingStatus();
        String processingMeasures = yiDTO.getProcessingMeasures();
        if (!processingStatus.equals("2") && processingMeasures != null && !processingMeasures.isEmpty()) {
            return new ResponseData<>().ok(yiMapper.updateByFinish(yiDTO));
        }
        return new ResponseData<>().fail(ResponseEnum.FAIL);
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData<?> delete(String id) {
        return new ResponseData<>().ok(yiMapper.delete(id));
    }

    /**
     * 常规修改方法
     *
     * @param yiDTO
     * @return
     */
    @Override
    public ResponseData<?> update(YiDTO yiDTO) {
        return new ResponseData<>().ok(yiMapper.update(yiDTO));
    }

    /**
     * 批量删除操作
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseData<?> batchDelete(List<String> ids) {
        return new ResponseData<>().ok(yiMapper.batchDelete(ids));
    }

    /**
     * 异常子页面查全部
     *
     * @param id
     * @return
     */
    @Override
    public ResponseData<?> queryOthersById(String id) {
        return new ResponseData<>().ok(yiMapper.queryOthersById(id));
    }

    /**
     * 异常子页面的保存功能
     *
     * @param yiDTO
     * @return
     */
    @Override
    public ResponseData<?> saveData(YiDTO yiDTO) {
        return new ResponseData<>().ok(yiMapper.saveData(yiDTO));
    }

    /**
     * 导出功能
     *
     * @param response
     * @return
     */
    @SneakyThrows
    @Override
    public ResponseData<?> exportYiData(HttpServletResponse response) {
        List<Map<String, Object>> yiData = yiMapper.queryException2(null);

        // 字段名与中文表头的映射关系
        Map<String, String> fieldToChineseMap = new HashMap<>();
        fieldToChineseMap.put("id", "异常单号");
        fieldToChineseMap.put("processing_time", "处理时间");
        fieldToChineseMap.put("event_location", "事件地点");
        fieldToChineseMap.put("companyName", "合作商");
        fieldToChineseMap.put("event_description", "事件说明");
        fieldToChineseMap.put("remark", "异常描述");
        fieldToChineseMap.put("event_type", "事件状态");
        fieldToChineseMap.put("processing_status", "异常状态");
        fieldToChineseMap.put("tel", "联系方式");
        fieldToChineseMap.put("carNum", "车牌号");
        fieldToChineseMap.put("event_time", "事件时间");
        fieldToChineseMap.put("report_time", "上报时间");
        fieldToChineseMap.put("driverName", "司机");
        fieldToChineseMap.put("processing_measures", "处理措施");
        fieldToChineseMap.put("customer_id", "客户编码");
        fieldToChineseMap.put("status", "运单状态");
        fieldToChineseMap.put("user_id", "用户编码");


        exportService.exportDynamicDataToExcel(response, yiData, fieldToChineseMap);

        return new ResponseData<>().ok();
    }

    /**
     * 导入功能
     *
     * @param file
     * @return
     */
    @SneakyThrows
    @Override
    public ResponseData<?> importYiData(MultipartFile file) {
        // 直接读取 Excel 内容到 List<YiData>
        List<YiData> dataList = EasyExcel.read(file.getInputStream())
                .head(YiData.class)
                .sheet()
                .doReadSync();

        // 遍历数据列表，逐条插入数据库
        for (YiData yiData : dataList) {
            yiMapper.addByYiChang(yiData);
        }

        return new ResponseData<>().ok(dataList);
    }

    @Override
    public ResponseData<?> updateImg(String id, String images) {
        return new ResponseData<>().ok(yiMapper.updateImg(id, images));
    }

    @Override
    public ResponseData<?> queryByWaybillDTO(PageData<WaybillDTO> pageData) {
        PageHelper.startPage(pageData.getPageNum(), pageData.getPageSize());
        List<WaybillDTO> yiDTOS = yiMapper.queryByWaybillDTO(pageData.getParam());
        PageInfo pageInfo = new PageInfo(yiDTOS);
        return new ResponseData<>().ok(pageInfo);
    }

    @Override
    public ResponseData<?> queryWaybillById(String id) {
        return new ResponseData<>().ok(yiMapper.queryByWaybillId(id));
    }
}